package com.log.enhance.aspect;

import com.log.enhance.config.LogContext;
import lombok.extern.slf4j.XSlf4j;

/**
 * 日志线程上下文
 *
 * @author Mr_wenpan@163.com 2021/05/29 12:12
 */
@XSlf4j
public final class LogThreadContext {

    /**
     * 用于存放每个线程的logBean
     */
    public final static ThreadLocal<LogThreadContext> LOG_THREAD_CONTEXT = new InheritableThreadLocal<>();

    /**
     * 当前方法的日志上下文
     */
    private LogContext currentLogContext;

    /**
     * 获取当前线程的日志上下文
     *
     * @return com.log.enhance.aspect.LogThreadContext
     * @date 2021/5/29 12:18 下午
     * @author wenpan
     */
    public static LogThreadContext getLogThreadContext() {
        // 先从当前线程的threadlocal中获取一下日志上下文
        LogThreadContext logThreadContext = LOG_THREAD_CONTEXT.get();
        // 如果当前线程中还没有放入日志上下文，则创建一个放进去
        if (logThreadContext == null) {
            logThreadContext = new LogThreadContext();
            LOG_THREAD_CONTEXT.set(logThreadContext);
        }
        return logThreadContext;
    }

    protected void clear() {
        //防止内存泄漏  改成在AddTraceIdFilter 进行删除
        LOG_THREAD_CONTEXT.remove();
    }

    public LogContext getCurrentLogContext() {
        return currentLogContext;
    }

    public void setCurrentLogContext(LogContext currentLogContext) {
        this.currentLogContext = currentLogContext;
    }
}
